#include "opengldraw.h"

#include <GL/glut.h>
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>

void drawRectangle(const Rectangle& rect, int r, int g, int b)
{
    glPushMatrix();
        //TODO: Translating the Coordinate System or using x and y directly in the Vertex function?
        glTranslatef(rect.getX(), rect.getY(), 0.0);
        glColor3ub(r, g, b);
        glBegin(GL_QUADS);
            glVertex2f(0.0, 0.0);
            glVertex2f(rect.getWidth(), 0.0);
            glVertex2f(rect.getWidth(), rect.getHeight());
            glVertex2f(0.0, rect.getHeight());
        glEnd();
    glPopMatrix();
}


void drawBall(const Ball& ball, int r, int g, int b) {

    int sections = 30;
    GLfloat twoPi = 2.0f * M_PI;

    glPushMatrix();
        glTranslatef(ball.getX(), ball.getY(), 0.0);
        glColor3ub(r, g, b);

        glBegin(GL_TRIANGLE_FAN);

        glVertex2f(0.0, 0.0); // origin
        for(int i = 0; i <= sections; i++) { // make $section number of circles
                glVertex2f(ball.getRadius() * cos(i *  twoPi / sections),
                        ball.getRadius() * sin(i * twoPi / sections));
        }

        glEnd();


    glPopMatrix();

}

void drawCannon(const Cannon& cannon, float angle) {
	//Kanonenrohr
	glPushMatrix();
	
	glColor3ub(191,191,191);
	glTranslatef(cannon.getX(), cannon.getY(), 0);

	glPushMatrix();
	glRotatef(angle, 0, 0, 1);

    glColor3ub(125, 125, 125);
	glBegin(GL_QUADS);
        glVertex2f(60, 0);
        glVertex2f(60, 20);
        glVertex2f(0, 20);
        glVertex2f(0, 0);
	glEnd();	
	glPopMatrix();
    //Kanonenrad
    glColor3ub(139,69,19);
    glScalef(20, 20, 1);
	
    glBegin(GL_POLYGON);
        for(int i = 0; i < 50; ++i){
            glVertex2f(sin(2 * M_PI / 50 * i), cos (2 * M_PI / 50 * i));
        }
    glEnd();

	glPopMatrix();
}

void drawTower(Tower& tower) {

    for(int i = 0; i < 11; i++) {
        const Target& t = tower.getTarget(i);
        if(t.health() == 0) continue;
        drawRectangle(static_cast<Rectangle>(t), 125, 125, 125);
    }


}

void drawExplosion(Explosion &explosion) {


    if(explosion.getTimer() <= 0)
        return;

    // scale factor
    const float s = explosion.getSize();

    glColor3ub(255, 255, 0);
    glPushMatrix();
    glTranslatef(explosion.getX(), explosion.getY(), 0);

    glBegin(GL_TRIANGLE_FAN);

    glVertex2f(0.0f, 0.0f);

    glVertex2f(2.0f*s, 0.0f);
    glVertex2f(0.5f*s, 0.5f*s);
    glVertex2f(0.0f, 2.0f*s);

    glVertex2f(-0.5f*s, 0.5f*s);
    glVertex2f(-2.0f*s, 0.0f);

    glVertex2f(-0.5f*s, -0.5f*s);

    glVertex2f(0.0f, -2.0f*s);
    glVertex2f(0.5f*s, -0.5f*s);

    glVertex2f(2.0f*s, 0.0f);

    glEnd();

    glPopMatrix();

    explosion.decreaseTimer();

}
